package app.domain.geojson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GeoLineStringDTO {
    private String type;
    private List<Double[]> coordinates;

    public String getType() {
        return type;
    }

    public List<Double[]> getCoordinates() {
        return coordinates;
    }

    public void setCoordinates(List<Double[]> coordinates) {
        this.coordinates = coordinates;
    }

    public static final String TYPE = "LineString";

    private void init() {
        this.type = TYPE;
    }

    public GeoLineStringDTO(List<Double[]> coordinates) {
        init();
        this.coordinates = coordinates;
    }

    public GeoLineStringDTO() {
        init();
        coordinates = Collections.emptyList();
    }

    public static GeoLineStringDTO generateEmptyInstance() {
        return new GeoLineStringDTO(Collections.emptyList());
    }

    public static GeoLineStringDTO fromJsonStr(String json) {
        JsonNode tree;
        JsonNode array;
        String type;
        List<Double[]> points;
        ObjectMapper objectMapper;

        objectMapper = new ObjectMapper();
        tree = null;
        try {
            tree = objectMapper.readTree(json);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (null == tree) {
            String errMsg = String.format("内部数据错误1: 无法解析LineString: '%s'", json);
            System.out.println(errMsg);
            return GeoLineStringDTO.generateEmptyInstance();
        }
        type = tree.get("type").asText("");
        if (!StringUtils.equals(type, GeoLineStringDTO.TYPE)) {
            String errMsg = String.format("内部数据错误2: 无法解析LineString: type=='%s'", type);
            System.out.println(errMsg);
            return GeoLineStringDTO.generateEmptyInstance();
        }
        array = tree.get("coordinates");
        if (null == array || !array.isArray()) {
            return GeoLineStringDTO.generateEmptyInstance();
        }
        points = new ArrayList<>();
        for (int i = 0; i != array.size(); ++i) {
            JsonNode point = array.get(i);
            double x = point.get(0).asDouble();
            double y = point.get(1).asDouble();
            points.add(new Double[]{x, y});
        }
        return new GeoLineStringDTO(points);
    }

    @Override
    public String toString() {
        return "type=" + type + ", coordinates=" + coordinates;
    }
}
